//
//  authPersonal.m
//  HappyStore
//
//  Created by 李小辉 on 16/6/24.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "authPersonal.h"

@interface authPersonal ()<UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (strong, nonatomic) UITextField *nameTextField;

@property (strong, nonatomic) UITextField *IDcardTextField;

@property (strong, nonatomic) UIImageView *userInfoImageView;

@property (strong, nonatomic) UIButton *imageBtn;

@property (strong, nonatomic) UILabel *imageLabel;

@property (strong, nonatomic) UILabel *autoLabel;
@end

@implementation authPersonal

- (UIImageView *)userInfoImageView{
    if (!_userInfoImageView) {
        _userInfoImageView = [[UIImageView alloc] init];
    }
    return _userInfoImageView;
}


- (UILabel *)imageLabel{
    if (!_imageLabel) {
        _imageLabel = [[UILabel alloc] init];
    }
    return _imageLabel;
}

- (UILabel *)autoLabel{
    if (!_autoLabel) {
        _autoLabel = [[UILabel alloc] init];
    }
    return _autoLabel;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"白色背景"] forBarMetrics:UIBarMetricsDefault];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //title
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 190, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.text = @"实名认证";
    titleLabel.textColor = RGB(45, 45, 45);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    
    //设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"返回" highImage:@"返回"];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    //右rightBarButtonItem
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(btnRefer)];
    rightBar.tintColor = RGB(45, 45, 45);
    self.navigationItem.rightBarButtonItem = rightBar;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupView];
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}
-(void)leftBarButtonItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}
//配置视图
- (void)setupView{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 64, screenW, 1)];
    view.backgroundColor = RGB(236, 235, 235);
    [self.view addSubview:view];
    
    //真实姓名
    UILabel *nameLabel = [[UILabel alloc] init];
    [nameLabel setFont:[UIFont systemFontOfSize:16]];
    nameLabel.textColor = RGB(46, 45, 45);
    nameLabel.text = @"真实姓名";
    CGSize nameLabelSize = [nameLabel sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
    nameLabel.frame = CGRectMake(8, 16 + 64, nameLabelSize.width, nameLabelSize.height);
    [self.view addSubview:nameLabel];
    //姓名textField
    self.nameTextField = [[UITextField alloc] initWithFrame:CGRectMake(nameLabel.x + nameLabel.width + 10, nameLabel.y, screenW-nameLabel.x-nameLabel.width, nameLabel.height)];
    self.nameTextField.textColor = RGB(117, 117, 117);
    [self.view addSubview:self.nameTextField];
    
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, nameLabel.y+nameLabel.height +16, screenW, 1)];
    view1.backgroundColor = RGB(236, 235, 235);
    [self.view addSubview:view1];
    
    //省份证
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, view1.y + 1 + 10, screenW, 1)];
    view2.backgroundColor = RGB(236, 235, 235);
    [self.view addSubview:view2];
    
    UILabel *IDcardLabel = [[UILabel alloc] init];
    [IDcardLabel setFont:[UIFont systemFontOfSize:16]];
    IDcardLabel.textColor = RGB(46, 45, 45);
    IDcardLabel.text = @"身份证号码";
    CGSize IDcardSize = [IDcardLabel sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
    IDcardLabel.frame = CGRectMake(8, view2.y + 1 + 16, IDcardSize.width, IDcardSize.height);
    [self.view addSubview:IDcardLabel];
    
    //省份证textField
    self.IDcardTextField = [[UITextField alloc] initWithFrame:CGRectMake(IDcardLabel.x+IDcardLabel.width + 10, IDcardLabel.y, screenW-IDcardLabel.width-IDcardLabel.x, IDcardLabel.height)];
    self.IDcardTextField.textColor = RGB(117, 117, 117);
    self.IDcardTextField.keyboardType = UIKeyboardTypeNamePhonePad;
    [self.view addSubview:self.IDcardTextField];
    
    UIView *view3 = [[UIView alloc] initWithFrame:CGRectMake(0, IDcardLabel.y+ IDcardLabel.height + 16, screenW, 1)];
    view3.backgroundColor = RGB(236, 235, 235);
    [self.view addSubview:view3];
    
    //名片
    
    self.userInfoImageView.frame = CGRectMake(8, view3.y + 1 + 20, screenW - 16, 234);
    self.userInfoImageView.layer.borderWidth = 1.0f;
    self.userInfoImageView.backgroundColor = [UIColor clearColor];
    self.userInfoImageView.layer.borderColor = RGB(236, 235, 235).CGColor;
    [self.view addSubview:self.userInfoImageView];
    
    self.imageBtn = [[UIButton alloc] init];
    self.imageBtn.frame = self.userInfoImageView.frame;
    self.imageBtn.backgroundColor = [UIColor clearColor];
    [self.imageBtn setImage:[UIImage imageNamed:@"加入"] forState:UIControlStateNormal];
    self.imageBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    [self.imageBtn addTarget:self action:@selector(referImage) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.imageBtn];
    
    self.autoLabel.text = @"上传您的名片，已完成认证";
    self.autoLabel.textAlignment = NSTextAlignmentCenter;
    self.autoLabel.font = [UIFont systemFontOfSize:16];
    self.autoLabel.textColor = RGB(46, 45, 45);
    self.autoLabel.frame = CGRectMake(0, self.userInfoImageView.y + self.userInfoImageView.height - 30 - 20, screenW, 21);
    [self.view addSubview:self.autoLabel];
    
    self.imageLabel.text = @"图片不得大于5MB,支持JPG,JPEG,PNG";
    self.imageLabel.textAlignment = NSTextAlignmentCenter;
    self.imageLabel.font = [UIFont systemFontOfSize:12];
    self.imageLabel.textColor = RGB(179, 178, 178);
    self.imageLabel.frame = CGRectMake(0, self.userInfoImageView.y + self.userInfoImageView.height - 30, screenW, 21);
    [self.view addSubview:self.imageLabel];
}


//点击按钮上传图片

- (void)referImage{
    
    self.autoLabel.text = @"";
    self.imageLabel.text = @"";
    [self.imageBtn setImage:nil forState:UIControlStateNormal];
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"照片选择"
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"相机",@"相册", nil];
    [actionSheet showInView:self.view];
}

#pragma mark - 选择照片
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //先设定sourceType为相机，然后判断相机是否可用（ipod）没相机，不可用将sourceType设定为相片库
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
    pickerImage.delegate = self;
    pickerImage.allowsEditing = YES;//设置可编辑
    switch (buttonIndex) {
        case 0:
        {
            NSLog(@"相机");
            pickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:pickerImage animated:YES completion:nil];//进入照相界面
        }
            break;
        case 1:
        {
            NSLog(@"相册");
            pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //图片库
            [self presentViewController:pickerImage animated:YES completion:nil];//进入照相界面
        }
            break;
        case 2:
        {
            if (!self.userInfoImageView.image) {
                self.autoLabel.text = @"上传您的名片，已完成认证";
                self.imageLabel.text = @"图片不得大于5MB,支持JPG,JPEG,PNG";
                [self.imageBtn setImage:[UIImage imageNamed:@"加入"] forState:UIControlStateNormal];
            }
            
            NSLog(@"取消");
        }
            break;
    }
    
}

//点击相册中的图片 货照相机照完后点击use  后触发的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    //    [_btnUserImg setImage:image forState:UIControlStateNormal];
    //    _btnUserImg.layer.masksToBounds = YES;
    //    _btnUserImg.layer.cornerRadius = 20.0;
    /* 此处info 有六个值
     * UIImagePickerControllerMediaType; // an NSString UTTypeImage)
     * UIImagePickerControllerOriginalImage;  // a UIImage 原始图片
     * UIImagePickerControllerEditedImage;    // a UIImage 裁剪后图片
     */
    // 保存图片至本地，方法见下文
    //    NSString *strName = [NSString stringWithFormat:@"%@.jpg",[self dateString]];
    //    [self saveImage:image withName:strName];
    [self.userInfoImageView setImage:image];
    if (!self.userInfoImageView.image) {
        self.autoLabel.text = @"上传您的名片，已完成认证";
        self.imageLabel.text = @"图片不得大于5MB,支持JPG,JPEG,PNG";
        [self.imageBtn setImage:[UIImage imageNamed:@"加入"] forState:UIControlStateNormal];
    }
    
    
}

//点击cancel 调用的方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

#pragma mark 照片的时间名称
- (NSString*)dateString
{
    NSMutableString*string=[[NSMutableString alloc] init];
    NSDate*dayDate=[NSDate date];
    NSDateFormatter*dayFormatter=[[NSDateFormatter alloc] init];
    [dayFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStrings= [dayFormatter stringFromDate:dayDate];
    NSArray*dayArray=[dateStrings componentsSeparatedByString:@"-"];
    for (int i=0; i<[dayArray count]; i++) {
        [string appendFormat:@"%@",[dayArray objectAtIndex:i]];
    }
    NSDate*timeDate=[NSDate date];
    NSDateFormatter*timeFormatter=[[NSDateFormatter alloc] init];
    [timeFormatter setDateFormat:@"HH:mm:ss:SSS"];
    NSString *timeString= [timeFormatter stringFromDate:timeDate];
    NSArray*timeArray=[timeString componentsSeparatedByString:@":"];
    for (int i=0; i<[timeArray count]; i++) {
        [string appendFormat:@"%@",[timeArray objectAtIndex:i]];
    }
    return string;
    
}


#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.1);
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}

#pragma mark - 提交
- (void)btnRefer{

        BOOL isOK = YES;
        
       
        if (self.nameTextField.text.length == 0) {
                isOK = NO;

            [self showSingleIconBubble:@"请输入真实姓名"];
            }
        if (isOK) {
            isOK = [self.IDcardTextField.text isValidIdCardNum];
            if (!isOK) {

                [self showSingleIconBubble:@"请输入正确的身份证号码"];

                }
            }
        if (isOK) {
            if (self.userInfoImageView.image == nil) {
                isOK = NO;

                [self showSingleIconBubble:@"请添加名片照片"];

                }
            }
        
        if (isOK) {
            //token=验证用户&userId=用户id&userType=用户类型 （1-个人 2-企业 3-政府）&trueName=真实姓名&trueCard=身份证号
            [self showRoundProgressWithTitle:@"请稍后..."];
            NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
            [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
            [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"userId"];
            [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"usertype"] forKey:@"userType"];//用户类型
            
    
                [muDicParameters setObject:self.nameTextField.text forKey:@"trueName"];//真实姓名
                [muDicParameters setObject:self.IDcardTextField.text forKey:@"trueCard"];//身份证号
           
        
            NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"authUser_app_myHome.im.lensum"];
            
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            
            [manager POST:strURl parameters:muDicParameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
               //压缩
                NSMutableArray *aryImg = [NSMutableArray arrayWithObjects:self.userInfoImageView.image, nil];
                NSMutableArray *muSaveFull = [NSMutableArray array];
                for (int i = 0; i<aryImg.count; i++) {
                    UIImage *image = aryImg[i];
                    NSString *strName1 = [NSString stringWithFormat:@"%@.png",[self dateString]];
                    [self saveImage:image withName:strName1];
                    NSString *fullPath1 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:strName1];
                    [muSaveFull addObject:fullPath1];
                }
                
                
                NSString *zippedPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip",[self dateString]]];
                
                BOOL isSucee = [SSZipArchive createZipFileAtPath:zippedPath withFilesAtPaths:muSaveFull];
                if (isSucee) {
                    NSData *data1 = [NSData dataWithContentsOfFile:zippedPath];
                    [formData appendPartWithFileData:data1 name:@"photos" fileName:@"photos.zip" mimeType:@"zip"];
                }
                
            } progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                
                NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
//                NSLog(@"%@",dicInfo);
                if ([dicInfo[@"result"] integerValue] == 1) {
                    [self performSelector:@selector(dismissVC) withObject:nil afterDelay:kHideHudDelay];
                    [self showRightWithTitle:dicInfo[@"msg"] autoCloseTime:2];

                }else {

                    [self showRightWithTitle:dicInfo[@"msg"] autoCloseTime:2];
                }

            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

                [self showSingleIconBubble:error.localizedDescription];

            }];
            
        }

}
- (void)dismissVC
    {
        [self.navigationController popViewControllerAnimated:YES];
    }

@end
